<template>
  <div class="admin-layout">
    <AdminHeader />
    <div class="main-wrapper">
      <AdminNavbar />
      <div class="content-wrapper">
        <div class="stop-order-container">
          <div class="page-header">
            <h2>停止订单执行</h2>
            <div class="header-actions">
              <el-input
                v-model="searchKeyword"
                placeholder="搜索订单号/产品型号/客户名称"
                class="search-input"
                clearable
                @keyup.enter="handleSearch"
              >
                <template #suffix>
                  <el-icon class="el-input__icon" @click="handleSearch">
                    <Search />
                  </el-icon>
                </template>
              </el-input>
              <el-button type="primary" @click="refreshData">
                <el-icon><Refresh /></el-icon> 刷新
              </el-button>
            </div>
          </div>

          <div class="running-orders-panel">
            <div class="panel-header">
              <h3>正在执行的订单</h3>
            </div>
            <div class="panel-content" v-loading="ordersLoading">
              <div
                v-if="filteredOrders.length === 0"
                class="empty-placeholder"
              >
                暂无正在执行的订单
              </div>
              <div
                v-for="order in filteredOrders"
                :key="order.orderId"
                class="order-card"
              >
                <div class="order-header">
                  <div class="order-number">订单号: {{ order.orderNumber }}</div>
                  <el-tag type="success">{{ order.status }}</el-tag>
                </div>
                <div class="order-info">
                  <div class="info-item">
                    <span class="label">产品型号:</span>
                    <span class="value">{{ order.productModel }}</span>
                    <span class="label">数量:</span>
                    <span class="value">{{ order.quantity }}</span>
                  </div>
                  <div class="info-item">
                    <span class="label">色温参数:</span>
                    <span class="value">{{ order.colorTemp }}</span>
                  </div>
                  <div class="info-item">
                    <span class="label">客户:</span>
                    <span class="value">{{ order.customer }}</span>
                    <span class="label">联系方式:</span>
                    <span class="value">{{ order.customerPhone }}</span>
                  </div>
                  <div class="info-item">
                    <span class="label">交付日期:</span>
                    <span class="value">{{ formatDate(order.endtime) }}</span>
                  </div>
                  <div class="info-item">
                    <span class="label">已生产数量:</span>
                    <span class="value">{{ order.count || 0 }}</span>
                  </div>
                  <div class="info-item">
                    <span class="label">生产线ID:</span>
                    <span class="value highlight">{{ order.orderBylineId }}</span>
                  </div>
                </div>
                <div class="order-actions">
                  <el-button type="danger" @click="handleStopOrder(order)">
                    <el-icon><CircleClose /></el-icon> 停止执行
                  </el-button>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 停止确认对话框 -->
    <el-dialog
      v-model="stopDialogVisible"
      title="停止订单执行确认"
      width="400px"
    >
      <div class="stop-confirm">
        <el-icon class="warning-icon"><Warning /></el-icon>
        <p>确定要停止订单 "{{ currentOrder?.orderNumber }}" 在生产线 {{ currentOrder?.orderBylineId }} 上的执行吗？</p>
        <p class="warning-text">此操作将中断生产流程，请确认是否继续。</p>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="stopDialogVisible = false">取消</el-button>
          <el-button type="danger" @click="confirmStopOrder">确认停止</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import AdminHeader from '@/components/AdminHeader.vue'
import AdminNavbar from '@/components/AdminNavbar.vue'
import { Search, Refresh, CircleClose, Warning } from '@element-plus/icons-vue'
import { getRunningOrders, removeOrderFromLine } from '@/api/production'

// 数据定义
const orders = ref([])
const ordersLoading = ref(false)
const searchKeyword = ref('')
const stopDialogVisible = ref(false)
const currentOrder = ref(null)

// 过滤后的订单列表
const filteredOrders = computed(() => {
  if (!searchKeyword.value) return orders.value

  const keyword = searchKeyword.value.toLowerCase()
  return orders.value.filter(order =>
    (order.orderNumber && order.orderNumber.toLowerCase().includes(keyword)) ||
    (order.productModel && order.productModel.toLowerCase().includes(keyword)) ||
    (order.customer && order.customer.toLowerCase().includes(keyword))
  )
})

// 获取正在执行的订单列表
const fetchOrders = async () => {
  ordersLoading.value = true
  try {
    const res = await getRunningOrders()
    if (res.success) {
      orders.value = res.data || []
    } else {
      ElMessage.error(res.message || '获取正在执行的订单列表失败')
    }
  } catch (error) {
    console.error('获取正在执行的订单列表失败', error)
    ElMessage.error('获取正在执行的订单列表失败')
  } finally {
    ordersLoading.value = false
  }
}

// 刷新数据
const refreshData = () => {
  fetchOrders()
}

// 搜索处理
const handleSearch = () => {
  // 过滤由计算属性处理
}

// 打开停止订单确认对话框
const handleStopOrder = (order) => {
  currentOrder.value = order
  stopDialogVisible.value = true
}

// 确认停止订单执行
const confirmStopOrder = async () => {
  if (!currentOrder.value) return

  try {
    const res = await removeOrderFromLine(currentOrder.value.orderId)
    if (res.success) {
      ElMessage.success('订单已停止执行')
      stopDialogVisible.value = false
      refreshData() // 刷新数据
    } else {
      ElMessage.error(res.message || '停止订单执行失败')
    }
  } catch (error) {
    console.error('停止订单执行失败', error)
    ElMessage.error('停止订单执行失败')
  }
}

// 格式化日期
const formatDate = (dateStr) => {
  if (!dateStr) return ''
  const date = new Date(dateStr)
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
}

// 组件挂载时获取数据
onMounted(() => {
  refreshData()
})
</script>

<style scoped>
.admin-layout {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background: #f5f7f9;
}

.main-wrapper {
  flex: 1;
  display: flex;
  overflow: hidden;
}

.content-wrapper {
  flex: 1;
  padding: 24px;
  overflow: auto;
  background: #fff;
  margin: 16px;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
}

.stop-order-container {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.search-input {
  width: 250px;
}

.running-orders-panel {
  display: flex;
  flex-direction: column;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  overflow: hidden;
  height: calc(100vh - 250px);
}

.panel-header {
  padding: 15px;
  background-color: #f5f7fa;
  border-bottom: 1px solid #e4e7ed;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.panel-header h3 {
  margin: 0;
  font-size: 16px;
  color: #303133;
}

.panel-content {
  flex: 1;
  padding: 15px;
  overflow-y: auto;
  background-color: #f9fafc;
}

.empty-placeholder {
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  color: #909399;
  font-size: 14px;
}

.order-card {
  background-color: #fff;
  border-radius: 4px;
  padding: 15px;
  margin-bottom: 15px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  transition: all 0.3s;
  position: relative;
}

.order-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px 0 rgba(0, 0, 0, 0.1);
}

.order-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.order-number {
  font-weight: bold;
  font-size: 15px;
}

.order-info {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.info-item {
  display: flex;
  align-items: center;
}

.label {
  color: #606266;
  margin-right: 8px;
  min-width: 80px;
}

.value {
  color: #303133;
  margin-right: 20px;
}

.value.highlight {
  color: #409eff;
  font-weight: bold;
}

.order-actions {
  margin-top: 15px;
  display: flex;
  justify-content: flex-end;
}

.stop-confirm {
  text-align: center;
}

.warning-icon {
  font-size: 48px;
  color: #e6a23c;
  margin-bottom: 15px;
}

.warning-text {
  color: #f56c6c;
  margin-top: 10px;
}

.dialog-footer {
  margin-top: 20px;
  text-align: right;
}
</style>